/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.appointment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.appointment.service.AppointmentInfoService;
import com.jeeplus.appointment.service.dto.AppointmentInfoDTO;
import com.jeeplus.appointment.service.mapstruct.AppointmentInfoWrapper;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 预约信息Controller
 * @author xx
 * @version 2023-12-30
 */

@Api(tags = "预约信息")
@RestController
@RequestMapping(value = "/appointment/appointmentInfo")
public class AppointmentInfoController {

    @Autowired
    private AppointmentInfoService appointmentInfoService;

    @Autowired
    private AppointmentInfoWrapper appointmentInfoWrapper;

    /**
     * 预约信息列表数据
     */
    @ApiLog("查询预约信息列表数据")
    @ApiOperation(value = "查询预约信息列表数据")
    @PreAuthorize("hasAuthority('appointment:appointmentInfo:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<AppointmentInfoDTO>> list(AppointmentInfoDTO appointmentInfoDTO, Page<AppointmentInfoDTO> page) throws Exception {
        List<RoleDTO> roleDTOS = UserUtils.getCurrentUserDTO().getRoleDTOList();
        if (!CollectionUtils.isEmpty(roleDTOS)) {
            if (roleDTOS.stream().anyMatch(role -> "patient".equals(role.getEnName()))) {
                appointmentInfoDTO.setPatientId(UserUtils.getCurrentUserDTO().getId());
            } else if (roleDTOS.stream().anyMatch(role -> "doctor".equals(role.getEnName()))) {
                appointmentInfoDTO.setDoctorId(UserUtils.getCurrentUserDTO().getId());
            }
        }

        QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition(appointmentInfoDTO, AppointmentInfoDTO.class);
        IPage<AppointmentInfoDTO> result = appointmentInfoService.findPage(page, queryWrapper);
        return ResponseEntity.ok(result);
    }


    /**
     * 根据Id获取预约信息数据
     */
    @ApiLog("根据Id获取预约信息数据")
    @ApiOperation(value = "根据Id获取预约信息数据")
    @PreAuthorize("hasAnyAuthority('appointment:appointmentInfo:view','appointment:appointmentInfo:add','appointment:appointmentInfo:edit')")
    @GetMapping("queryById")
    public ResponseEntity<AppointmentInfoDTO> queryById(String id) {
        return ResponseEntity.ok(appointmentInfoService.findById(id));
    }

    /**
     * 保存预约信息
     */
    @ApiLog("保存预约信息")
    @ApiOperation(value = "保存预约信息")
    @PreAuthorize("hasAnyAuthority('appointment:appointmentInfo:add','appointment:appointmentInfo:edit')")
    @PostMapping("save")
    public ResponseEntity<String> save(@Valid @RequestBody AppointmentInfoDTO appointmentInfoDTO) {
        //新增或编辑表单保存
        appointmentInfoService.saveOrUpdate(appointmentInfoWrapper.toEntity(appointmentInfoDTO));
        return ResponseEntity.ok("保存预约信息成功");
    }


    /**
     * 删除预约信息
     */
    @ApiLog("删除预约信息")
    @ApiOperation(value = "删除预约信息")
    @PreAuthorize("hasAuthority('appointment:appointmentInfo:del')")
    @DeleteMapping("delete")
    public ResponseEntity<String> delete(String ids) {
        String idArray[] = ids.split(",");
        appointmentInfoService.removeByIds(Lists.newArrayList(idArray));
        return ResponseEntity.ok("删除预约信息成功");
    }

    /**
     * 导出预约信息数据
     * @param appointmentInfoDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出预约信息数据")
    @PreAuthorize("hasAnyAuthority('appointment:appointmentInfo:export')")
    @GetMapping("export")
    public void exportFile(AppointmentInfoDTO appointmentInfoDTO, Page<AppointmentInfoDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition(appointmentInfoDTO, AppointmentInfoDTO.class);
        if (ExportMode.current.equals(options.getMode())) { // 导出当前页数据

        } else if (ExportMode.selected.equals(options.getMode())) { // 导出选中数据
            queryWrapper.in("a.id", options.getSelectIds());
        } else { // 导出全部数据
            page.setSize(-1);
            page.setCurrent(0);
        }
        List<AppointmentInfoDTO> result = appointmentInfoService.findPage(page, queryWrapper).getRecords();
        EasyExcelUtils.newInstance(appointmentInfoService, appointmentInfoWrapper).exportExcel(result, options.getSheetName(), AppointmentInfoDTO.class, fileName, options.getExportFields(), response);
    }

    /**
     * 导入预约信息数据
     * @return
     */
    @PreAuthorize("hasAnyAuthority('appointment:appointmentInfo:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance(appointmentInfoService, appointmentInfoWrapper).importExcel(file, AppointmentInfoDTO.class);
        return ResponseEntity.ok(result);
    }

    /**
     * 下载导入预约信息数据模板
     * @param response
     * @return
     */
    @PreAuthorize("hasAnyAuthority('appointment:appointmentInfo:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "预约信息数据导入模板.xlsx";
        List<AppointmentInfoDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance(appointmentInfoService, appointmentInfoWrapper).exportExcel(list, "预约信息数据", AppointmentInfoDTO.class, fileName, null, response);
    }

}
